package com.seelyn.dowork.security;

import com.seelyn.dowork.entities.User;
import com.seelyn.dowork.entities.UserExample;
import com.seelyn.dowork.repositories.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @author Siva
 */
@Component
public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger LOG = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Autowired
    UserMapper repo;

    @Override
    public UserDetails loadUserByUsername(String email) {

        UserExample userExample = new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        List<User> user = repo.selectByExample(userExample);

        LOG.info("Email: {}, User: {}", email, user);
        if (user == null) {
            throw new UsernameNotFoundException("User not found");
        }
        return new SecurityUser(user.get(0));
    }

}
